package com.zhy.mysocketdemo;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
//import com.google.gson.JsonObject;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.text.BreakIterator;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private String url = "wss://sy876r670000.test.connect.paymentsense.cloud/pac?token=12164861-bcae-4ce4-9ac4-338b9048f26c&api-version=v1&software-house-id=spxus&installer-id=001";
    //    private String url = "ws://192.168.5.122:8080/ws/asset";
    private WebSocketClient webSocketClient;
    private TextView tv;
    private StringBuilder sb = new StringBuilder();
    private static String TAG = "Socket";


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
//            sb.append(msg.obj.toString());
//            sb.append("\n");
////            tv.setText(sb.toString());
//
            Gson gson = new Gson();
//
//            SocketLogBean socketLogBean = gson.fromJson(msg.obj.toString(), SocketLogBean.class);
//
//            if (socketLogBean.getParams() != null) {
//                String a = socketLogBean.getParams().getNotificationValue();
//                tv.setText(tv.getText().toString() + "\n" + a);
//            } else {
//                SocketSuccessBean socketSuccessBean = gson.fromJson(msg.obj.toString(), SocketSuccessBean.class);
//                String b = socketSuccessBean.getResult().getTransactionResult();
//                tv.setText(tv.getText().toString() + "\n" +"最终结果\n"+ b);
//            }


            Log.d(TAG, msg.obj.toString());

            try {
                JSONObject jsonObject=new JSONObject(msg.obj.toString());
                if(jsonObject.has("method")){
                    SocketLogBean socketLogBean = gson.fromJson(msg.obj.toString(), SocketLogBean.class);
                    if(socketLogBean.getMethod().equals("signatureVerificationRequest")){
                        tv.setText(tv.getText().toString() + "\n" + socketLogBean.getMethod()+":"+socketLogBean.getParams().getNotificationValue());
                    }else {
                        tv.setText(tv.getText().toString() + "\n" + socketLogBean.getMethod()+":"+socketLogBean.getParams().getNotificationValue());
                    }

                }else if(jsonObject.has("result")){
                    SocketSuccessBean socketSuccessBean = gson.fromJson(msg.obj.toString(), SocketSuccessBean.class);
                    tv.setText(tv.getText().toString() + "\n" + socketSuccessBean.getResult().getTransactionResult());
                }else if(jsonObject.has("error")) {
                    SocketErrorBean socketErrorBean = gson.fromJson(msg.obj.toString(), SocketErrorBean.class);
                    tv.setText(tv.getText().toString() + "\n" + socketErrorBean.getError().getMessage());
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return true;
        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);

        findViewById(R.id.bt_success).setOnClickListener(v -> {
            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \"63213442\", \"currency\": \"GBP\", \"amount\": 10000 },\"id\": 0 }";
            tv.setText(tv.getText().toString() + "\n"+"成功：");

            if(webSocketClient.isOpen()){
                webSocketClient.send(str);
            }



        });

        findViewById(R.id.bt_xs).setOnClickListener(v -> {
            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"refund\", \"params\": { \"tid\": \"63213442\", \"currency\": \"GBP\", \"amount\": 50000 },\"id\": 0 }";
            tv.setText(tv.getText().toString() + "\n"+"超时：");
            webSocketClient.send(str);
        });

        findViewById(R.id.bt_fail).setOnClickListener(v -> {
            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \"VCMSPXUSIS0\", \"currency\": \"GBP\", \"amount\": 1000000 },\"id\": 0 }";
            tv.setText(tv.getText().toString() + "\n"+"失败：");
            webSocketClient.send(str);
        });


        URI serverURI = URI.create(url);

        webSocketClient = new WebSocketClient(serverURI) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {

            }

            @Override
            public void onMessage(String message) {
                Message handlerMessage = Message.obtain();
                handlerMessage.obj = message;
                handler.sendMessage(handlerMessage);

            }

            @Override
            public void onClose(int code, String reason, boolean remote) {

            }

            @Override
            public void onError(Exception ex) {

            }
        };
        webSocketClient.connect();
    }

}